import { ref } from 'vue'
import { defineStore } from 'pinia'
import cfg from '@/config/config'
import api from '@/api/student'
import type { PageConfig, StudentItem } from '@/config/types'
import type { StudentSearchForm } from '@/config/forms'


export const useStudentStore = defineStore('students', () => {
    const loading = ref<boolean>(false)
    const search = ref<StudentSearchForm>({
        field: 2,
        title: '',
        page: 1,
        limit: cfg.pageLimit
    })
    const students = ref<StudentItem[]>([])
    const pager = ref<PageConfig>({
        page: 1,
        pageSize: cfg.pageLimit,
        total: 0
    })
    const fields = [{
        id: 1,
        title: '姓名'
    }, {
        id: 2,
        title: '用户名'
    }, {
        id: 3,
        title: '手机号'
    }]

    const updating = ref(false)
    const student = ref<StudentItem | null>(null)

    async function loadStudents() {
        loading.value = true
        try {
            const res = await api.getList(search.value)
            students.value = res.data
            pager.value = {
                page: res.page,
                pageSize: res.size,
                total: res.total
            }
            loading.value = false
        } catch(e) {
            loading.value = false
        }
    }

    function changePage(page: number, size: number) {
        search.value.page = page
        search.value.limit = size
        loadStudents()
    }

    async function loadStudent(accountId : number) {
        updating.value = true
        try {
            const res = await api.getItem(accountId)
            student.value = res.data
            pager.value = {
                page: res.page,
                pageSize: res.size,
                total: res.total
            }
            updating.value = false
        } catch(e) {
            updating.value = false
        }
    }

    async function update() {
        if (student.value == null) return false

        updating.value = true
        let result = false
        try {
            const res = await api.update(student.value.accountId, {
                name: student.value.name,
                avatar: student.value.avatar,
                phone: student.value.phone,
                email: student.value.email,
                birthday: student.value.birthday,
                gender: student.value.gender,
                address: student.value.address,
                hobby: student.value.hobby
            })
            result = res.data
            updating.value = false
        } catch(e) {
            updating.value = false
        }
        return result
    }

    return {
        loading,
        search,
        pager,
        fields,
        students,
        loadStudents,
        changePage,

        updating,
        student,
        loadStudent,
        update,
    }
})